import {
  Collapse,
  Space,
  Descriptions,
  Pagination,
  message,
  Button,
  Row,
  Col,
  Card,
} from "antd";
import React from "react";
import {
  DownCircleOutlined,
  UpCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  CaretLeftOutlined,
  CaretRightOutlined
} from "@ant-design/icons";
import { routerRedux } from "dva/router";
import styles from "./style.less";
import icon from "../../assets/images/admob.png";
import { connect } from "dva";
import Search from "antd/lib/input/Search";
import { ReadingIncrement } from "./echarts";
import Chart from "../../components/Chart";
import { color } from "echarts";
const { Panel } = Collapse;
const menuList = [
  {
    title: "自然科学",
    id: 1,
    children: [
      {
        id: 101,
        title: "数学"
      },
      {
        id: 102,
        title: "物理"
      },
      {
        id: 103,
        title: "化学"
      }
    ]
  },
  {
    title: "农业科学",
    id: 2,
    children: [
      {
        id: 201,
        title: "农业"
      },
      {
        id: 202,
        title: "林业"
      },
      {
        id: 203,
        title: "畜牧业"
      }
    ]
  }
];
const typeList = [];
const sortList = ["发布日期", "点击量"];
@connect(({ global }) => ({ userId: global.userId }))
class Standard extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 0,
      pageSize: 5,
      typeIndex: -1,
      allTypeIndex: 1,
      sortIndex: -1,
      standardList: [],
      total: 0,
      typeList: [],
      menuList: [],
      subject: "",
      type: "",
      visitNum: 0,
      releaseTime: 0,
      inputValue: "",
      showIcon: false,
      show: <ArrowUpOutlined />,
      chartsData: [],//关联的数据
      hotStandList: []//热点标准排行
    };
  }
  componentDidMount = () => {
    this.getByType();
    this.queryCategory();
    this.getStandardInfoByPage();
    this.getStandDetailInfoRank()
    this.getRelatedData()
  };
  //获取关联
  getRelatedData = () => {
    this.props.dispatch({
      type: "global/getAssociationInfo",
      payload: {
        query: ""
      }
    }).then(res => {
      console.log(res);
      if (res) {
        this.setState({
          chartsData: res.data
        })
      }
    })
  }
  //获取排行
  getStandDetailInfoRank = () => {
    this.props.dispatch({
      type: "global/getStandDetailInfoRank",
      payload: {
        num: 10
      }
    }).then(res => {
      if (res) {
        this.setState({
          hotStandList: res.data
        })
      }
    })
  }
  //获取头部分类
  getByType = () => {
    this.props
      .dispatch({
        type: "global/getByType",
        payload: {
          type: "STANDARDTYPE"
        }
      })
      .then(res => {
        // console.log("getByType", res.data);
        if (res) {
          this.setState({
            typeList: res.data
          });
        }

      });
  };
  //左侧分类
  queryCategory = () => {
    this.props
      .dispatch({
        type: "global/queryCategory",
        payload: {
          pid: 2
        }
      })
      .then(res => {
        // console.log("queryCategory", res.data);
        if (res) {
          this.setState({
            menuList: res.data
          });
        }

      });
  };
  //标准列表
  getStandardInfoByPage = () => {
    let {
      pageSize,
      currentPage,
      subject,
      tile,
      type,
      visitNum,
      releaseTime
    } = this.state;
    this.props
      .dispatch({
        type: "global/getStandardInfoByPage",
        payload: {
          pageSize: pageSize,
          currentPage: currentPage === 0 ? 1 : currentPage,
          subject: subject,
          query: tile,
          type: type,
          visitNum: visitNum,
          releaseTime: releaseTime
        }
      })
      .then(res => {
        if (res && res.data.length > 0) {
          this.setState({
            standardList: res.data.rows,
            total: res.data.total,
            id: res.data.id
          });
        } else {
          if (res) {
            this.setState({
              standardList: res.data.rows,
              total: res.data.total,
              id: res.data.id
            });
          }

        }
      });

  };
  //分页
  pageChange = (page, pageSize) => {
    console.log("页码改变", page, pageSize);
    this.setState({ pageSize: pageSize, currentPage: page }, () => {
      this.getStandardInfoByPage();
    });
  };
  pageSizeChange = (current, size) => {
    console.log("pageSize改变", current, size);
    this.setState({ pageSize: size, currentPage: 1 }, () => {
      this.getStandardInfoByPage();
    });
  };
  //搜索
  onSearch = value => {
    this.setState(
      {
        tile: value,
        currentPage: 1
      },
      () => {
        this.getStandardInfoByPage();
        this.props.dispatch({
          type: "global/getAssociationInfo",
          payload: {
            query: this.state.tile
          }
        }).then(res => {
          console.log(res);
          if (res) {
            this.setState({
              chartsData: res.data
            })
          }
        })
      }
    );
  };
  inputChange = e => {
    this.setState({
      inputValue: e.target.value
    });
  };
  getClear = () => {
    this.setState({
      inputValue: ""
    });
  };
  //展开
  handleSpreadOut = (index) => {
    this.setState({
      dataIndex: index
    })
  }
  //下载
  download = fileUrl => {
    if (fileUrl !== "") {
      this.props.dispatch({
        type: "global/download",
        payload: {
          path: `${fileUrl}`
        }
      })
        .then(blob => {
          console.log("文件流", blob);
          let filename = fileUrl.split("/")[fileUrl.split("/").length - 1]
          // // let filename = decodeURI(headers["content-disposition"].split(";")[1].split("filename=")[1]);
          // let blob = new Blob(['\uFEFF' +data])
          // console.log("blob对象",blob);
          const link = document.createElement('a')
          link.download = filename
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(link.href)
          document.body.removeChild(link)

          this.getStandardInfoByPage();
        });
    } else {
      message.error("下载资源不存在");
    }
  };
  handleToSearch = dicCode => {
    console.log(dicCode);
    this.setState(
      {
        subject: dicCode,
        isShow: dicCode,
        currentPage: 1
      },
      () => {
        this.getStandardInfoByPage();
        console.log(this.state.isShow);
      }
    );
  };

  handleTypeChange = (dicCode, e) => {
    console.log(dicCode);
    this.setState(
      {
        typeIndex: Number(e.target.getAttribute("data-index")),
        currentPage: 1
      },
      () => {
        this.setState(
          {
            type: dicCode,
            allTypeIndex: 0
          },
          () => {
            this.getStandardInfoByPage();
          }
        );
      }
    );
  };
  allhandleTypeChange = e => {
    if (this.state.allTypeIndex === 0) {
      this.setState(
        {
          allTypeIndex: 1,
          type: "",
          typeIndex: -1,
          currentPage: 1
        },
        () => {
          this.getStandardInfoByPage();
        }
      );
    }
  };
  handleSortChange = e => {
    this.setState(
      {
        sortIndex: Number(e.target.getAttribute("data-index")),
        showIcon: true,
        currentPage: 1
      },
      () => {
        if (this.state.sortIndex === 0) {
          if (this.state.releaseTime === 0) {
            this.setState(
              {
                releaseTime: 1,
                show: <ArrowUpOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          } else if (this.state.releaseTime === 1) {
            this.setState(
              {
                releaseTime: 2,
                show: <ArrowDownOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          } else if (this.state.releaseTime === 2) {
            this.setState(
              {
                releaseTime: 1,
                show: <ArrowUpOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          } else if (this.state.visitNum === 0) {
            this.setState(
              {
                releaseTime: 1,
                show: <ArrowUpOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          } else if (this.state.visitNum === 1) {
            this.setState(
              {
                releaseTime: 1,
                show: <ArrowUpOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          }
        }
        if (this.state.sortIndex === 1) {
          if (this.state.visitNum === 0) {
            this.setState(
              {
                visitNum: 1,
                show: <ArrowUpOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          } else if (this.state.visitNum === 1) {
            this.setState(
              {
                visitNum: 2,
                show: <ArrowDownOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          } else if (this.state.visitNum === 2) {
            this.setState(
              {
                visitNum: 1,
                show: <ArrowUpOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          } else if (this.state.releaseTime === 0) {
            this.setState(
              {
                visitNum: 1,
                show: <ArrowUpOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          } else if (this.state.releaseTime === 1) {
            this.setState(
              {
                visitNum: 1,
                show: <ArrowUpOutlined />
              },
              () => {
                this.getStandardInfoByPage();
              }
            );
          }
        }
        console.log(this.state.sortIndex);
      }
    );
  };

  handleToDetaile = id => {
    console.log(id);
    // this.props.dispatch(
    //     routerRedux.push({
    //     pathname: `/standardDetail/${id}`,
    //     state: {}
    //   }),
    // );
    window.open( window.BASE_URL + `/standardDetail/${id}`)
  };
  //关联点击
  onChartClick = (e) => {
    console.log(e);
    this.handleToDetaile(e.data.key)
  }
  render() {
    const {
      typeIndex,
      sortIndex,
      allTypeIndex,
      currentPage,
      isShow,
      showIcon,
      show,
      chartsData,
    } = this.state;
    return (
      <div className={styles.content}>
        <div className={styles.bannerBox}>
          <div className={styles.bannerTitle}>
            <p>标准与规范</p>
            <p>Standards and specifications</p>
          </div>
        </div>
        <div className={styles.contentBody}>
          <div className={styles.clearfix}>
            <div className={styles.fl} style={{ width: "25%" }}>
              {/* 数据关联 */}
              <div className={styles.detailBodyRightTop}
                style={{ width: "100%", height: "auto", background: "white", borderRadius: "10px", marginBottom: "20px", padding: "20px", position: "relative" }}>
                {/* <p className={styles.detailBodyRightTitle}
                style={{fontWeight:"500",lineHeight:"25px",color:"#4A5B64"}}>数据关联</p> */}
                <div className={styles.chartBox}
                  style={{ height: "280px" }}>
                  <Chart
                    option={ReadingIncrement(chartsData, 0)}
                    onChartClick={this.onChartClick}
                  />
                </div>
              </div>
              <div className={styles.leftContent}>
                <Collapse bordered={false}>
                  {this.state.menuList.length > 0 ? (
                    this.state.menuList.map((item, index) => {
                      return (
                        <Panel header={item.dicName} key={index}>
                          {item.childList.map((item, index) => {
                            return (
                              <p
                                key={index}
                                className={
                                  isShow === item.dicCode
                                    ? `${styles.colloractive}`
                                    : ``
                                }
                                onClick={() =>
                                  this.handleToSearch(item.dicCode)
                                }
                              >
                                {item.dicName}
                              </p>
                            );
                          })}
                        </Panel>
                      );
                    })
                  ) : (
                    <Panel showArrow={false}></Panel>
                  )}
                </Collapse>
              </div>
              <div style={{ width: "100%", background: "white", borderRadius: "10px", marginBottom: "20px", padding: "20px 0 10px 0", position: "relative" }}>
                <p style={{ textAlign: "center", fontSize: "30px" }}>
                  <CaretLeftOutlined style={{ color: "#1abcc7" }} />标准点击量排行<CaretRightOutlined style={{ color: "#1abcc7" }} />
                </p>
                <ul style={{ listStyle: "none" }}>
                  {
                    this.state.hotStandList.map((item, index) => {
                      return <li key={index} style={{ marginBottom: "10px", fontSize: `20px`, width: "200px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }} title={item.tile}>
                        <a style={{ color: `${'#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).substr(-6)}` }} onClick={() => this.handleToDetaile(item.id)}>{item.num}-{item.tile}</a>
                      </li>
                    })
                  }
                </ul>
              </div>
            </div>
            <div className={styles.fl} style={{ width: "75%" }}>
              <div className={styles.rightContent}>
                <div className={styles.rightContentHead}>
                  <div className={styles.searchBox}>
                    <Search
                      placeholder="请输入查询内容"
                      onSearch={this.onSearch}
                      onChange={e => this.inputChange(e)}
                      value={this.state.inputValue}
                    />
                    <Button style={{ height: "50px" }} onClick={this.getClear}>
                      清空
                    </Button>
                  </div>
                  <div className={styles.typeList}>
                    <Space>
                      <span className={styles.listLable}>分类：</span>
                      <span
                        className={allTypeIndex === 1 ? `${styles.active}` : ""}
                        onClick={e => this.allhandleTypeChange(e)}
                      >
                        全部
                      </span>
                      {this.state.typeList.map((item, index) => {
                        return (
                          <span
                            key={index}
                            data-index={index}
                            className={
                              typeIndex === index ? `${styles.active}` : ""
                            }
                            onClick={e =>
                              this.handleTypeChange(item.dicCode, e)
                            }
                          >
                            {item.dicName}
                          </span>
                        );
                      })}
                    </Space>
                  </div>
                </div>
                <div className={styles.sortBox}>
                  <div className={styles.clearfix}>
                    <div className={styles.fl}>
                      <Space>
                        {sortList.map((item, index) => {
                          return (
                            <div
                              key={index}
                              data-index={index}
                              className={
                                sortIndex === index
                                  ? `${styles.active} ${styles.sortBtn}`
                                  : `${styles.sortBtn}`
                              }
                              onClick={e => this.handleSortChange(e)}
                            >
                              {item}
                              <span
                                style={{ display: showIcon ? "block" : "none" }}
                              >
                                <span
                                  style={{
                                    display:
                                      sortIndex === index ? "block" : "none",
                                    paddingLeft: "73px",
                                    marginTop: "-29px"
                                  }}
                                >
                                  {show}
                                </span>
                              </span>
                            </div>
                          );
                        })}
                      </Space>
                    </div>
                    <div className={styles.fr}>
                      <p>
                        共检索到
                        <span className={styles.num}>{this.state.total}</span>
                        个项目
                      </p>
                    </div>
                  </div>
                </div>
                <div className={styles.listBox}>
                  {this.state.standardList.map((item, index) => {
                    return (
                      <div
                        key={index}
                        data-index={index}
                        className={styles.descriptionsBox}
                        style={{ marginBottom: "2%" }}
                      >
                        <div className={styles.descriptionsHead}>
                          <div className={styles.clearfix}>
                            <div className={styles.fl}>
                              <div className={styles.descriptionsIcon}>
                                {
                                  item.logo ?
                                    <img
                                      src={item.logo}
                                      alt=""
                                      style={{ width: "100%", height: "100%" }}
                                    />
                                    :
                                    item.tile.charAt(0)
                                }
                              </div>
                            </div>
                            <div className={styles.fl}>
                              <div className={styles.descriptionsTitle}>
                                <p
                                  onClick={() => this.handleToDetaile(item.id)}
                                  title={item.tile}
                                  // style={{ cursor: "pointer", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", marginTop: "20px" }}
                                  style={{ cursor: "pointer", marginTop: "20px" }}
                                >
                                  {item.num}-{item.tile}
                                </p>
                              </div>
                              <div className={styles.descriptionsNum}>
                                <Space size={40}>
                                  <span>
                                    发布时间：
                                    {item.releaseTime}
                                  </span>
                                  <span>点击量：{item.visitNum}</span>
                                  <span>标准状态：{item.behaviourName}</span>
                                </Space>
                              </div>
                            </div>
                            <div
                              className={styles.clearfix}
                              style={{ width: "100%", float: "right" }}
                            >
                              <span
                                className={`${styles.descriptionsBtn} ${styles.fr}`}
                                style={{ marginRight: "1rem" }}
                              >
                                <Button type="text" size="small" style={{ border: "1px solid #44c5bb", borderRadius: "4px", color: "#00b5c1" }} onClick={() => this.download(item.fileUrl)}>立即下载</Button>
                              </span>
                              <span
                                className={`${styles.descriptionsBtn} ${styles.fr}`}
                                style={{ marginRight: "1.5rem" }}
                              >
                                <Button type="text" size="small" style={{ border: "1px solid #44c5bb", borderRadius: "4px", color: "#00b5c1" }} onClick={() => this.handleToDetaile(item.id)}>进入详情</Button>
                              </span>
                            </div>
                          </div>
                        </div>
                        <div className={styles.descriptionsBody}>
                          <Descriptions column={2}>
                            <Descriptions.Item
                              label="起草人"
                              span={2}
                              className={styles.ulList}
                            >
                              <Row gutter={[24, 9]} style={{ width: "100%" }}>
                                {item.author
                                  .split(/[,，、 /]/)
                                  .map((item, index) => {
                                    return (
                                      <Col key={index} span={6}>
                                        {item}
                                      </Col>
                                    );
                                  })}
                              </Row>
                            </Descriptions.Item>

                            <Descriptions.Item label="标准号">
                              {item.num}
                            </Descriptions.Item>
                            <Descriptions.Item label="标准类别">
                              {item.typeName}
                            </Descriptions.Item>
                            <Descriptions.Item label="所属学科">
                              {item.subjectName}
                            </Descriptions.Item>
                            <Descriptions.Item label="发布日期">
                              {item.releaseTime}
                            </Descriptions.Item>
                          </Descriptions>

                          {
                            this.state.dataIndex == index ?
                              <Descriptions column={2}>
                                <Descriptions.Item label="实施日期">
                                  {item.effectDate}
                                </Descriptions.Item>
                                <Descriptions.Item label="废止日期">
                                  {item.endTime}
                                </Descriptions.Item>
                                <Descriptions.Item label="中国标准分类号">
                                  {item.chinaTypeNum}
                                </Descriptions.Item>
                                <Descriptions.Item label="国际标准分类号">
                                  {item.nationalTypeNum}
                                </Descriptions.Item>
                                <Descriptions.Item
                                  label="归口单位"
                                  span={2}
                                  className={styles.ulList}
                                >
                                  <ul>
                                    {item.unit
                                      .split(/[,，、 ]/)
                                      .map((item, index) => {
                                        return <li key={index}>{item}</li>;
                                      })}
                                  </ul>
                                </Descriptions.Item>
                                <Descriptions.Item label="执行单位" span={2}>
                                  {item.executeUnit}
                                </Descriptions.Item>
                                <Descriptions.Item
                                  label="主管部门"
                                  span={2}
                                  className={styles.ulList}
                                >
                                  <ul>
                                    {item.deft
                                      .split(/[,，、 ]/)
                                      .map((item, index) => {
                                        return <li key={index}>{item}</li>;
                                      })}
                                  </ul>
                                </Descriptions.Item>
                                <Descriptions.Item label="资产介绍" span={2}>
                                  {item.num}
                                </Descriptions.Item>
                                <Descriptions.Item span={2}>
                                  <Button style={{ color: "#44c5bb" }} type="link" onClick={() => this.setState({ dataIndex: -1 })}>收起<UpCircleOutlined size="middle" /></Button>
                                </Descriptions.Item>
                              </Descriptions>
                              :
                              <Descriptions>
                                <Descriptions.Item span={2}>
                                  <Button style={{ color: "#44c5bb" }} type="link" onClick={() => this.handleSpreadOut(index)}>展开<DownCircleOutlined size="middle" /></Button>
                                </Descriptions.Item>
                              </Descriptions>
                          }
                        </div>
                      </div>
                    );
                  })}
                  <div className={styles.pagination}>
                    <Pagination
                      total={this.state.total}
                      showSizeChanger
                      showQuickJumper
                      current={currentPage === 0 ? 1 : currentPage}
                      defaultCurrent={1}
                      defaultPageSize={5}
                      pageSizeOptions={[5, 10, 20, 50]}
                      showTotal={total => `共 ${total} 条`}
                      onChange={this.pageChange}
                      onShowSizeChange={this.pageSizeChange}
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Standard;
